var cusomerList;
$(function() {
	var customerColums = [ [ {
		field : 'id',
		title : 'customerId',
		hidden : true
	},{
		field : 'company',
		title : '单位',
		width : 120,
		align : 'center'
	},{
		field : 'receiver',
		title : '收货人',
		width : 90,
		align : 'center'
	}, {
		field : 'mobile',
		title : '联系方式',
		width : 90,
		align : 'center'
	}, {
		field : 'address',
		title : '地址',
		width : 233,
		align : 'center'
	}]];
	
	var now = new Date();
	var month = now.getMonth();
	var date = now.getDate();

	if (urlParam != '') {
		$('.forbuild').hide();
		register($('#bill_form .printTr'),'span_line');
		$('#bill_form  .goodsList').hide();
		utils.postJson({
					url : '/queryBillDetail',
					data : {
						billId : urlParam.split('=')[1]
					},
					success : function(response) {
						var data = response.result;
						var formObj = document.getElementById("bill_form");
						for	(var i = 0; i < formObj.length; i++) {
							if (data.bill[formObj[i].name]) {
								formObj[i].value = data.bill[formObj[i].name];
								var span = $(formObj[i]).next('.text');
								span.text(formObj[i].value);
							}
						}
						var tr = $('#bill_form  .goodsList')[0];
						$.each(data.billItemList,function(i, item) {
											$(tr).after('<tr class="goodsList"><td class="line_num">1</td><td class="spmc"><input name="goodsName"/></td><td class="gg"><input name="goodsType"/></td><td class="num sl"><input type="number"name="num" /></td><td class="dj"><input type="number"name="unitPrice"/></td><td class="money je"><input type="number"name="amount" /></td><td class="bz"><input name="remark"/></td></tr>');
											tr = $(tr).next()[0];
											register($(tr),'');
											$.each(item, function(key,value) {
												var input = $(tr).find('input[name=' + key+ ']');
												input.val(value);
												var span = $(input).next('.text');
												span.text(value);
											});
										});
						sumTotalMoney();
						$($('#bill_form  .goodsList')[0]).remove();
						sort();
						$('#billNo').text(data.bill.billNo);
						$('input').attr("disabled", "disabled");
					}
				});
	} else {
		hoverTr($('#bill_form  .goodsList'));
		register($('#bill_form  .goodsList'),'');
		register($('#bill_form .printTr'),'span_line');
		$('#billNo').text(utils.format(now, 'yyyyMMddHHmmss'));
		$('#print').click(function() {
			$.messager.confirm('提交', '确定保存订单吗?', function(r){
				if (r){
					var formData = utils.formForJson("bill_form",{amount:true,num:true,remark:true,goodsType:true,goodsName:true,unitPrice:true});
					formData.billNo = $('#billNo').text();
					utils.postJson({url:'/buildBill',data:formData,success:function(response){
//						$.messager.show({
//							title:'提示',
//							msg:,
//							timeout:5000,
//							showType:'slide'
//						});
						
						var printArr = [];
						var style = $('#tableStyle')[0].outerHTML;
						getPrintHtml(style,printArr);
						print(printArr);
						
						$.messager.alert('提示','订单'+formData.billNo+'已生成','Warning',function(){
							location.reload();
						});
					}});
				}
			});
		});
	}
	$('#onlyprint').click(function(){
		var printArr = [];
		var style = $('#tableStyle')[0].outerHTML;
		getPrintHtml(style,printArr);
		print(printArr);
	});
		
		$('#company').keyup(function(e){
			if(e.keyCode==13){
				utils.postJson({url:'/queryCustomerList',data:{company:this.value},success:function(response){
					var list = response.result.rows;
					if(list.length > 1){
						$("#cusomerListDialog").dialog({
				    		title: '客户选择',
				    	    width: 550,
				    	    height: 180,
				    	    close: false,
				    	    cache: false,
				    	    modal: true
						});
						if(cusomerList == null){
							cusomerList = $("#cusomerList").datagrid({
								columns : customerColums,
								onDblClickRow:function(rowIndex, rowData){
									$.each(rowData,function(key,value){
										$('#bill_form').find('input[name='+key+']').val(value);
										$('#bill_form').find('input[name='+key+']').next('.text').text(value);
									});
									$('#bill_form').find('input[name=customerId]').val(rowData.id);
									$("#cusomerListDialog").dialog('close');
								}
							});
						}
						cusomerList.datagrid('loadData',response.result);
					}else if(list.length == 1){
						$.each(list[0],function(key,value){
							$('#bill_form').find('input[name='+key+']').val(value);
							$('#bill_form').find('input[name='+key+']').next('.text').text(value);
						});
						$('#bill_form').find('input[name=customerId]').val(list[0].id);
					}else{
						$.messager.alert('提示','客户还未录入','Warning');
					}
				}});
			}
		});
	});
	
	function getPrintHtml(style,printArr){
		$('#bill_form .goodsList').find('td input').hide();
		$('#bill_form .printTr').find('td input').hide();
		$('#bill_form .goodsList').find('td .text').show();
		$('#bill_form .printTr').find('td .text').show();
		
		if($('#bill_form .goodsList').length>8){
			//分页
			var arr = buildPrintHtml();
			$.each(arr,function(i,subHtml){
				printArr.push(style+subHtml);
			});
		}else{
			var html = $('#bill_form').html();
			printArr.push(style+html);
		}
		
		$('#bill_form .goodsList').find('td input').show();
		$('#bill_form .printTr').find('td input').show();
		$('#bill_form .goodsList').find('td .text').hide();
		$('#bill_form .printTr').find('td .text').hide();
	}
	
	function buildPrintHtml(){
		var arr = [];
		var size = $('#bill_form .goodsList').length;
		var pageSize = size%8==0?(size/8):(Math.floor(size/8)*1+1);
		for(var i=0;i<pageSize;i++){
			$('#printHtml .tmpTable').append($('#bill_form .tr1')[0].outerHTML);
			$('#printHtml .tmpTable').append($('#bill_form .tr2')[0].outerHTML);
			$('#printHtml .tmpTable').append($('#bill_form .tr3')[0].outerHTML);
			$('#printHtml .tmpTable').append($('#bill_form .tr4')[0].outerHTML);
			$('#printHtml .tmpTable').append('<tr><td colspan="6"><table class="table_style" cellpadding="0" cellspacing="0" border="0"><tr><td class="w45">项次</td><td class="spmc">品种名</td><td class="gg">规格</td>	<td class="sl">数量</td><td class="dj">单价</td><td class="je">小计</td><td class="bz">备注</td></tr></table>	</td></tr>');
			for(var j=0;j<8;j++){
				var index = i*8+j;
				if(index>size-1){
					break;
				}
				var goodsList = $('#bill_form .goodsList').eq(index);
				$('#printHtml .tmpTable table').append(goodsList[0].outerHTML);
			}
			$('#printHtml .tmpTable table').append($('#bill_form .tr5')[0].outerHTML);
			$('#printHtml .tmpTable').append($('#bill_form .tr6')[0].outerHTML);
			var tmpTable = $('#printHtml .tmpTable');
			arr.push(tmpTable[0].outerHTML);
			console.info(tmpTable[0].outerHTML);
			$('#printHtml .tmpTable').empty();
		}
		return arr;
	}
	
	function register(tr,addClass){
		$(tr).find('td input').after('<div class="text '+addClass+'">&nbsp;</div>');
		$(tr).find('td input').keyup(function(){
			$(this).next('.text').text($(this).val());
		});
	}
	function hoverTr(tr){
		$(tr).hover(function(){
			$(tr).find('.option').show();
		},function(){
			$(tr).find('.option').hide();
		});
	}
	function print(array){
		var LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
		for(var i=0;i<array.length;i++){
			LODOP.SET_PRINT_PAGESIZE(1,2150,1400,'Page'+i);
			LODOP.ADD_PRINT_HTM(0,0,2150,1400,array[i]);
			if(i!=array.length-1){
				LODOP.NewPage();
			}
		} 
		LODOP.PREVIEW();
	}

	function addTr(input) {
		if (this.event.keyCode == 13) {
			toAdd(input,'回车');
		}
	}
	function sort() {
		$('.line_num').each(function(index, input) {
			$(input).text(index + 1);
		});
	}
	function toAdd(input,type) {
		var tr = $(input).parent().parent();
		if(type==null){
			tr = tr.parent();
		}
		tr.after('<tr class="goodsList"><td class="line_num">1</td><td class="spmc"><input name="goodsName"/></td><td class="gg"><input name="goodsType"/></td><td class="num sl"><input type="number"name="num"onkeyup="sumNum(this)"/></td><td class="dj"><input type="number"name="unitPrice"onkeyup="sumMoney(this)"/></td><td class="money je"><input type="number"name="amount"onkeyup="sumTotalMoney()"/></td><td class="bz"style="position: absolute;"><input name="remark"onkeydown="addTr(this)"/><div class="option"style="display: none;"><span class="right_position"onclick="toAdd(this)"style="margin-left: 5px;">+</span><span class="right_position"onclick="removeTr(this)"style="margin-left: 5px;">-</span></div></td></tr>');
		hoverTr(tr.next());
		register(tr.next(),'');
		sort();
	}
	function removeTr(input) {
		var tr = $(input).parent().parent().parent();
		tr.remove();
		sort();
	}
	function sumNum(input) {
		sumMoney($(input).parent().next().find("input")[0]);
	}
	function sumMoney(input) {
		var dj = input.value == '' ? 0 : input.value;
		var sl = $(input).parent().prev().find("input").val();
		sl = sl == '' ? 0 : sl;
		$(input).parent().next().find("input").val(sl * dj);
		$(input).parent().next().find(".text").text(sl * dj);
		sumTotalMoney();
	}
	function sumTotalMoney() {
		var total = 0;
		$('.money input').each(function(index, amount) {
			total += amount.value * 1;
		});
		$('.t_money').text(total.toFixed(2)+"元");
	}